import React, { useState } from "react";
import "antd/dist/antd.css";
import { Select, Radio, Form, Input, Button, Table } from "antd";
import './index.scss';

import fetchDataFormServer from "./fetchDataFormServer";

const columns = [
  {
    title: "姓名",
    dataIndex: "name",
    key: "name",
  },
  {
    title: "性别",
    dataIndex: "gender",
    key: "gender",
    render: (text) => {
      console.log(text);
      if (text === "male") return "男";
      return "女";
    },
  },
  {
    title: "是否接触过前端",
    dataIndex: "fe",
    key: "fe",
    render: (text) => {
      console.log(text);
      if (text === 0) return "否";
      return "是";
    },
  },
];

const dataArr = {
  genderArr: [
    { value: "male", name: "男" },
    { value: "female", name: "女" },
  ],
  feArr: [
    { value: 1, name: "是" },
    { value: 0, name: "否" },
  ],
};

const SearchByForm = () => {
  const [form] = Form.useForm();
  const [data, setData] = useState([]);

  const getDatasource = async (query = {}) => {
    // 模拟从服务端获取数据
    // 这里已经实现好了，你只需要完成下面这行之后的逻辑
    return await fetchDataFormServer(query);
  };

  // 表单加载完成后就调用
  const onSearch = (query) => {
    getDatasource(query).then((resp) => {
      setData(resp);
    });
  };

  return (
    <>
      <Form
        form={form}
        name="advanced_search"
        className="ant-advanced-search-form"
        onFinish={onSearch}
      >
        <Form.Item
          name="name"
          label="姓名"
          required={true}
          rules={[
            {
              message: "请输入姓名",
            },
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="gender"
          label="性别"
          required={true}
          rules={[
            {
              message: "请输入性别",
            },
          ]}
        >
          <Select allowClear>
            {
              dataArr.genderArr.map((gender) => {
                return <Select.Option value={gender.value} key={gender.value}>{gender.name}</Select.Option>
              })
            }
          </Select>
        </Form.Item>
        <Form.Item
          name="fe"
          label="是否接触过前端"
        >
          <Radio.Group>
            {
              dataArr.feArr.map((fe) => {
                return <Radio value={fe.value} key={fe.value}>{fe.name}</Radio>
              })
            }
          </Radio.Group>
        </Form.Item>
        <Form.Item>
          <Button htmlType="submit">搜索</Button>
        </Form.Item>
      </Form>

      <Table dataSource={data} columns={columns} />
    </>
  );
};

export default SearchByForm;
